<?php
/**
 * $Id: file_wrapper.php 11 2010-11-24 22:10:53Z LEON $
 * $Author: LEON $
 * $LastChangedDate: 2010-11-24 22:10:53 +0000 (Wed, 24 Nov 2010) $
 * $Revision: 11 $
 */
namespace cmFly\utils;
class file_wrapper {
    protected $fp;
    protected $mode;
    protected $filename;
    protected $closed;
    protected function __construct() {
    }
    public static function open($filename,$mode='r') {
	$mode=strtolower($mode);
	$obj=new self();
	$obj->mode=$mode;
	if($mode[0]=='w') {
	    $mode[0]='a';
	}
	$obj->fp=fopen($filename,$mode);
	if(!$obj->fp) {
	    return false;
	}
	$obj->lock();
	switch($obj->mode[0]) {
	    case 'w':
		$obj->truncate(0);
		break;
	}
	return $obj;
    }
    public static function file_exists($filename) {
	return file_exists($filename);
    }
    public function seek($pos,$seek_type=SEEK_SET) {
	return fseek($this->fp,$pos,$seek_type);
    }
    public function read($length) {
	return fread($this->fp,$length);
    }
    public function lock() {
	return flock($this->fp,LOCK_EX);
    }
    public function write($str,$len=false) {
	if($len===FALSE) {
	    $len=strlen($str);
	}
	return fwrite($this->fp,$str,$len);
    }
    public function truncate($size) {
	return ftruncate($this->fp,$size);
    }

    public function unlock() {
	return flock($this->fp,LOCK_UN);
    }
    public function close() {
	if($this->fp) {
	    fclose($this->fp);
	}
	$this->closed=true;
    }
    public function get_mode() {
	return $this->mode;
    }
    public function __destruct() {
	if($this->closed) {
	    return;
	}
	$this->close();
    }
}
?>